﻿#include "WRWorkTcpCommServerObject.h"
#include "WRWorkTcpCommServerAffair.h"
#include "WRWorkTcpCommServerInterface.h"

#include "../WRWorkTcpCommConsts.h"

#include <QTextCodec>

//初始化工作TCP通讯服务器对象。
WRWorkTcpCommServerObject::WRWorkTcpCommServerObject(WRWorkTcpCommServerSession* owner, WRWorkTcpCommServerObjRef* target)
    : m_owner(owner), m_target(target), m_affairs(32), m_interfaces(256)
{
    for(WRu i = 0, l = m_affairs.count(); i < l; ++i)
    {
        m_affairs[i] = 0;
    }
    for(WRu i = 0, l = m_interfaces.count(); i < l; ++i)
    {
        m_interfaces[i] = 0;
    }
}
//清理当前对象所占用的相关资源。
WRWorkTcpCommServerObject::~WRWorkTcpCommServerObject(void)
{
    for(WRu i = 0, l = m_affairs.count(); i < l; ++i)
    {
        Affair affair = m_affairs[i];
        if (affair)
        {
            delete affair;
        }
    }
    for(WRu i = 0, l = m_interfaces.count(); i < l; ++i)
    {
        Interface interface = m_interfaces[i];
        if (interface)
        {
            delete interface;
        }
    }
}

//创建指定的事件。
WRWorkTcpCommServerAffair* WRWorkTcpCommServerObject::createAffair(WRWorkAffair* target)
{
    QMutexLocker lck(&m_mutex);
    int index = -1;
    for(WRu i = 0, l = m_affairs.count(); i < l; ++i)
    {
        if (!m_affairs[i])
        {
            index = (int)i;
            break;
        }
    }
    if (index == -1)
    {
        index = (int)m_affairs.count();
        Affars affairs(index + 32);
        for(int i = 0; i < index; ++i)
        {
            affairs[i] = m_affairs[i];
        }
        for(WRu i = index, l = affairs.count(); i < l; ++i)
        {
            affairs[i] = 0;
        }
        m_affairs = affairs;
    }

    WRWorkTcpCommServerAffair* affair = new WRWorkTcpCommServerAffair(this, index, target);
    m_affairs[index] = affair;
    return affair;
}
//删除指定的事务。
void WRWorkTcpCommServerObject::deleteAffair(int index)
{
    QMutexLocker lck(&m_mutex);
    m_affairs[index] = 0;
}

//执行关闭处理。
void WRWorkTcpCommServerObject::shutdown(void)
{
    for(WRu i = 0, l = m_affairs.count(); i < l; ++i)
    {
        Affair affair = m_affairs[i];
        if (affair)
        {
            affair->shutdown();
        }
    }
    for(WRu i = 0, l = m_interfaces.count(); i < l; ++i)
    {
        Interface interface = m_interfaces[i];
        if (interface)
        {
            interface->shutdown();
        }
    }
}

//处理接收到数据。
void WRWorkTcpCommServerObject::procData(const unsigned char* buf, int len)
{
    WR16u cmdType = WRBytes::read<WR16u>(buf);
    buf += 2;
    len -= 2;
    switch (cmdType)
    {
    case WRWorkTcpComm::WorkObjectIIQuery://接口查询
    {
        WR32s cmdSequence = WRBytes::read<WR32s>(buf);
        buf += 4;
        len -= 4;
        WR16u id = WRBytes::read<WR16u>(buf);
        buf += 8;
        len -= 8;
        QUuid uid = WRBytes::read<QUuid>(buf);
        //执行接口查询
        Interface interface = 0;
        for(WRu i = 0, l = m_interfaces.count(); i < l; ++i)
        {
            Interface interface2 = m_interfaces[i];
            if (interface2 && interface2->uuid() == uid)
            {
                interface = interface2;
                break;
            }
        }
        if (!interface)
        {
            switch (id)
            {
            case WRWorkTcpComm::StateSource:
                interface = m_target->queryStateSource(uid, this);
                break;
            case WRWorkTcpComm::EventSource:
                interface = m_target->queryEventSource(uid, this);
                break;
            case WRWorkTcpComm::DataSource:
                interface = m_target->queryDataSource(uid, this);
                break;
            case WRWorkTcpComm::TaskDealer:
                interface = m_target->queryTaskDealer(uid, this);
                break;
            case WRWorkTcpComm::WorkDealer:
                interface = m_target->queryWorkDealer(uid, this);
                break;
            default:
                break;
            }
            if (interface)
            {
                m_interfaces[interface->index()] = interface;
            }
        }
        //发送查询响应
        WRDataPacket* packet;
        if (interface)
        {
            QTextCodec* codec = QTextCodec::codecForName("UTF-8");
            QByteArray nameArray = codec->fromUnicode(interface->name());
            int fillLen = 0;
            if (nameArray.length() <= 4)
            {
                fillLen = 4 - nameArray.length();
            }
            else
            {
                int len = nameArray.length()  - 4;
                int remain = len % 8;
                if (remain > 0) fillLen = 8 - remain;
            }
            int cmdLen = 28 + nameArray.length() + fillLen;

            packet = WRDataPacket::create(cmdLen);
            char* p;
            packet->buffer(&p);

            WRBytes::write((WR32u)WRWorkTcpComm::FrameHeader, p);//帧头
            p += 4;
            WRBytes::write((WR32s)(cmdLen), p);//帧长度
            p += 4;
            WRBytes::write((WR16u)(m_target->index()), p);//工作对象索引
            p += 2;
            WRBytes::write((WR16u)WRWorkTcpComm::WorkObjectIIQuery, p);//类型（接口查询）
            p += 2;
            WRBytes::write((WR32s)(cmdSequence), p);//指令序号
            p += 4;
            WRBytes::write((WR16s)(interface->index()), p);//接口索引
            p += 2;
            WRBytes::write((WR16s)(nameArray.length()), p); //name
            p += 2;
            memcpy(p, nameArray.constData(), nameArray.length());
            p += nameArray.length();
            p += fillLen;
            WRBytes::write((WR32u)WRWorkTcpComm::FrameVersion, p);//版本
            p += 4;
            WRBytes::write((WR32u)WRWorkTcpComm::FrameTailor, p);//帧尾
        }
        else
        {
            packet = WRDataPacket::allocate<32>();
            char* p;
            packet->buffer(&p);

            WRBytes::write((WR32u)WRWorkTcpComm::FrameHeader, p);//帧头
            WRBytes::write((WR32s)(32), p + 4);//帧长度
            WRBytes::write((WR16u)(m_target->index()), p + 8);//工作对象索引
            WRBytes::write((WR16u)WRWorkTcpComm::WorkObjectIIQuery, p + 10);//类型（接口查询）
            WRBytes::write((WR32s)(cmdSequence), p + 12);//指令序号
            WRBytes::write((WR16s)(-1), p + 16);//接口索引
            WRBytes::write((WR16s)(0), p + 18); //name
            WRBytes::write((WR32u)WRWorkTcpComm::FrameVersion, p + 24);//版本
            WRBytes::write((WR32u)WRWorkTcpComm::FrameTailor, p + 28);//帧尾
        }
        if (!sendData(packet))
        {
            packet->release();
        }
    }
        break;
    case WRWorkTcpComm::WorkObjectIITreat://接口处理
    {
        WR16u index = WRBytes::read<WR16u>(buf);
        buf += 2;
        len -= 2;
        if (index < m_interfaces.count())
        {
            Interface interface = m_interfaces[index];
            if (!interface)
            {
                interface = m_target->queryInterface(index, this);
                m_interfaces[index] = interface;
            }
            if (interface)
            {
                interface->procData(buf, len);
            }
        }
    }
        break;
    case WRWorkTcpComm::WorkObjectAffair://工作事务
    {
        WR32s id = WRBytes::read<WR32s>(buf);
        buf += 4;
        len -= 4;
        WR16u index = WRBytes::read<WR16u>(buf);
        buf += 2;
        len -= 2;
        if (index < m_affairs.count())
        {
            Affair affair = m_affairs[index];
            if (affair && affair->id() == id)
            {
                affair->procData(buf, len);
            }
        }
    }
        break;
    default:
        break;
    }
}
